package com.zhudeshuai.zhudemolist.widget.PlayBox;

import android.content.Context;
import android.media.MediaPlayer;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatSeekBar;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.zhu.zhuCore.utils.LogUtil;
import com.zhudeshuai.zhudemolist.R;

import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 简易播放器
 *
 * @author zhudeshuai
 * @since 2018/7/11
 */

public class AudioPlayView extends FrameLayout {

	private ImageView mPlayPauseIv;
	private AppCompatSeekBar mSeekBar;

	//展示当前播放时间
	private TextView mCurPos;
	//展示总播放时间
	private TextView mTotalPos;
	//关闭按钮
	private ImageView mCloseIv;
	//播放控制器
	private MediaPlayer mMediaPlayer;
	//当前显示状态
	private boolean isPlay = false;
	//定时器，用于更新seekBar
	private Timer mTimer;

	public AudioPlayView(@NonNull Context context) {
		this(context, null);
	}

	public AudioPlayView(@NonNull Context context, @Nullable AttributeSet attrs) {
		super(context, attrs);
		initView(context);
	}

	private void initView(Context context) {
		View inflate = LayoutInflater.from(context).inflate(R.layout.layout_play_box, this);
		mPlayPauseIv = (ImageView) inflate.findViewById(R.id.iv_play_pause);
		mSeekBar = (AppCompatSeekBar) inflate.findViewById(R.id.seekBar);
		mCurPos = (TextView) inflate.findViewById(R.id.tv_cur_pos);
		mTotalPos = (TextView) inflate.findViewById(R.id.tv_total);
		mCloseIv = (ImageView) findViewById(R.id.iv_close);
		mPlayPauseIv.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				playOrPause();
			}
		});
		mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
				LogUtil.d("zhu","mMediaPlayer.getCurrentPosition():" + mMediaPlayer.getCurrentPosition());
				LogUtil.d("zhu","progress:" + progress);
				if (fromUser) {
					int curMsec = mMediaPlayer.getDuration() * progress / 100;
					mMediaPlayer.seekTo(curMsec);
					//更新当前时间点
					mCurPos.setText(formatTime(curMsec));
				}
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {

			}

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {

			}
		});
	}

	public void setOnCloseListener(OnClickListener onCloseListener) {
		if (mCloseIv != null) {
			mCloseIv.setOnClickListener(onCloseListener);
		}
	}

	/**
	 * 初始化方法
	 *
	 * @param path 文件路径
	 */
	public void initSource(String path) {
		if (mMediaPlayer == null) {
			mMediaPlayer = new MediaPlayer();
		} else {
			mMediaPlayer.reset();
		}
		try {
			mMediaPlayer.setDataSource(path);
			mMediaPlayer.prepareAsync();
			mSeekBar.setMax(100);
		} catch (Exception e) {
			e.printStackTrace();
		}
		mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
			@Override
			public void onPrepared(MediaPlayer mp) {
				mTotalPos.setText(formatTime(mMediaPlayer.getDuration()));
				isPlay = false;
				playOrPause();
			}
		});
		if (mTimer == null) {
			mTimer = new Timer();
		}
		mTimer.schedule(new TimerTask() {
			@Override
			public void run() {
				final int currentPosition = mMediaPlayer.getCurrentPosition();
				int progress = currentPosition * 100 / mMediaPlayer.getDuration();
				mSeekBar.setProgress(progress);
				mCurPos.post(new Runnable() {
					@Override
					public void run() {
						mCurPos.setText(formatTime(currentPosition));
					}
				});
			}
		}, 500, 1000);

	}

	public void playOrPause() {
		if (isPlay) {
			mMediaPlayer.pause();
			showPlay();
		} else {
			mMediaPlayer.start();
			showPause();
		}
		isPlay = !isPlay;
	}


	private void showPlay() {
		if (mPlayPauseIv != null) {
			mPlayPauseIv.setImageResource(R.drawable.icon_play);
		}
	}

	private void showPause() {
		if (mPlayPauseIv != null) {
			mPlayPauseIv.setImageResource(R.drawable.icon_pause);
		}
	}


	public void release() {
		if (mMediaPlayer != null) {
			if (mMediaPlayer.isPlaying()) {
				mMediaPlayer.stop();
			}
			mMediaPlayer.release();
			mMediaPlayer = null;
		}
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}
	}

	private String formatTime(int time) {
		int totalSeconds = time / 1000;
		int seconds = totalSeconds % 60;
		int minutes = (totalSeconds / 60) % 60;
		int hours = totalSeconds / 3600;
		return hours > 0 ? String.format(Locale.CHINESE, "%02d:%02d:%02d", hours, minutes,
				seconds) : String.format(Locale.CHINESE, "%02d:%02d", minutes, seconds);

	}

}
